package com.shujia.hadoop.mr;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

public class MR08 {
    public static class MapJoin extends Mapper<LongWritable,Text,Text,NullWritable>{
        HashMap<String,String> stus =new HashMap<String,String>();

        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            FileSystem fs = FileSystem.get (context.getConfiguration ( ));
            Path path = new Path ("/students.txt");
            FSDataInputStream open = fs.open (path);
            BufferedReader br = new BufferedReader (new InputStreamReader (open));
            String line;
            while((line=br.readLine ())!=null){
                stus.put (line.split (",")[0],line);

            }
            super.setup (context);
        }

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString ( );
            String[] split = line.split (",");
            String id = split[0];
            String stu = stus.get (id);
            String str=stu+","+split[2];
            context.write (new Text (str),NullWritable.get ());
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Job job = Job.getInstance ( );
        job.setNumReduceTasks (0);
        job.setJobName ("mapjoin");
        job.setJarByClass (MR08.class);
        job.setMapperClass (MapJoin.class);
        job.setMapOutputKeyClass (Text.class);
        job.setMapOutputValueClass (NullWritable.class);
        Path input = new Path ("/score.txt");
        FileInputFormat.addInputPath (job,input);
        Path output = new Path ("/output1");
        FileOutputFormat.setOutputPath (job,output);
        job.waitForCompletion (true);

    }
}
